package TCP.TCP3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    //绑定服务器IP和端口号
    public TcpEchoClient(String IP, int port) throws IOException {
        socket = new Socket(IP, port);
    }
    //启动客户端
    public void start() {
        Scanner in = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            while(true) {
                //1.从控制台输入请求
                System.out.print("->");
                String request = in.next();
                //2.将请求发给服务器;
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                //刷新缓冲区
                printWriter.flush();
                //3.接收响应
                Scanner input = new Scanner(inputStream);
                String response = input.next();
                //4.打印响应
                System.out.println("->" + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
